/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sfoutils;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.util.zip.*;
import org.apache.commons.codec.binary.Base64;


/**
 *
 * @author rejun001
 */
public class SFOUtils
{

    String memento = "<gids-designer:root xmlns:gids-designer='http://www.fenestra.com/schemas/gids-designer' >"
            + "<gids-designer:cons-v>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='2' joined-cell-count-v='1' joined-cell-index-h='0' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:custom-content-cell-data content-id='1D695906-B4BE-7C7D-E040-18ACC9603D92' relative-index='4' />"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' border-bottom-style='solid' "
            + "border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' border-left-width='51398fu' "
            + "border-right-color='transparent' border-right-style='solid' border-right-width='0fu' border-top-color='transparent' "
            + "border-top-style='solid' border-top-width='0fu' font-color='black' font-decoration='no-underline' "
            + "font-family='Univers LT 55' font-rotation-angle='0' font-size='815848fu' font-style='normal' font-weight='400' "
            + "has-goomer='false' has-leader='false' horz-alignment='center' padding-bottom='0fu' padding-left='0fu' "
            + "padding-right='0fu' padding-top='0fu' vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='2' joined-cell-count-v='1' joined-cell-index-h='1' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:null-cell-data/>"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' border-bottom-style='solid' "
            + "border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' border-left-width='51398fu' "
            + "border-right-color='transparent' border-right-style='solid' border-right-width='0fu' border-top-color='transparent' "
            + "border-top-style='solid' border-top-width='0fu' font-color='black' font-decoration='no-underline' "
            + "font-family='Univers LT 55' font-rotation-angle='0' font-size='815848fu' font-style='normal' font-weight='400' "
            + "has-goomer='false' has-leader='false' horz-alignment='center' padding-bottom='0fu' padding-left='0fu' "
            + "padding-right='0fu' padding-top='0fu' vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:row-info can-break-before-v='false' cell-size-v='1218877fu' />"
            + "<gids-designer:empty-list/>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "<gids-designer:cons-v>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='2' joined-cell-count-v='1' joined-cell-index-h='0' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:custom-content-cell-data content-id='1D695906-B081-7C7D-E040-18ACC9603D92' relative-index='4' />"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' border-bottom-style='solid' "
            + "border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' border-left-width='51398fu' "
            + "border-right-color='transparent' border-right-style='solid' border-right-width='0fu' border-top-color='transparent' "
            + "border-top-style='solid' border-top-width='0fu' font-color='black' font-decoration='no-underline' "
            + "font-family='Univers LT 55' font-rotation-angle='0' font-size='815848fu' font-style='normal' font-weight='400' "
            + "has-goomer='false' has-leader='false' horz-alignment='center' padding-bottom='0fu' padding-left='0fu' "
            + "padding-right='0fu' padding-top='0fu' vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='2' joined-cell-count-v='1' joined-cell-index-h='1' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:null-cell-data/>"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' "
            + "border-bottom-style='solid' border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' "
            + "border-left-width='51398fu' border-right-color='transparent' border-right-style='solid' border-right-width='0fu' "
            + "border-top-color='transparent' border-top-style='solid' border-top-width='0fu' font-color='black' "
            + "font-decoration='no-underline' font-family='Univers LT 55' font-rotation-angle='0' font-size='815848fu' "
            + "font-style='normal' font-weight='400' has-goomer='false' has-leader='false' horz-alignment='center' "
            + "padding-bottom='0fu' padding-left='0fu' padding-right='0fu' padding-top='0fu' vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:row-info can-break-before-v='false' cell-size-v='1218877fu' />"
            + "<gids-designer:empty-list/>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "<gids-designer:cons-v>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='1' joined-cell-count-v='1' joined-cell-index-h='0' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:custom-content-cell-data content-id='1D695906-AE44-7C7D-E040-18ACC9603D92' relative-index='4' />"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' "
            + "border-bottom-style='solid' border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' "
            + "border-left-width='51398fu' border-right-color='transparent' border-right-style='solid' border-right-width='0fu' "
            + "border-top-color='transparent' border-top-style='solid' border-top-width='0fu' font-color='black' "
            + "font-decoration='no-underline' font-family='Univers LT 55' font-rotation-angle='0' font-size='815848fu' "
            + "font-style='normal' font-weight='400' has-goomer='false' has-leader='false' horz-alignment='center' "
            + "padding-bottom='0fu' padding-left='0fu' padding-right='0fu' padding-top='0fu' vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:cell-info joined-cell-count-h='1' joined-cell-count-v='1' joined-cell-index-h='0' "
            + "joined-cell-index-v='0' >"
            + "<gids-designer:custom-content-cell-data content-id='1D695906-AEB1-7C7D-E040-18ACC9603D92' relative-index='4' />"
            + "<gids-designer:cell-format background-color='form-background' border-bottom-color='black' "
            + "border-bottom-style='solid' border-bottom-width='51398fu' border-left-color='black' border-left-style='solid' "
            + "border-left-width='51398fu' border-right-color='transparent' border-right-style='solid' "
            + "border-right-width='0fu' border-top-color='transparent' border-top-style='solid' border-top-width='0fu' "
            + "font-color='black' font-decoration='no-underline' font-family='Univers LT 55' font-rotation-angle='0' "
            + "font-size='815848fu' font-style='normal' font-weight='400' has-goomer='false' has-leader='false' "
            + "horz-alignment='center' padding-bottom='0fu' padding-left='0fu' padding-right='0fu' padding-top='0fu' "
            + "vert-alignment='center' />"
            + "</gids-designer:cell-info>"
            + "<gids-designer:cons>"
            + "<gids-designer:row-info can-break-before-v='false' cell-size-v='1218877fu' />"
            + "<gids-designer:empty-list/>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "</gids-designer:cons>"
            + "<gids-designer:empty-v>"
            + "<gids-designer:col-info cell-size-h='5242640fu' />"
            + "<gids-designer:empty-v>"
            + "<gids-designer:col-info cell-size-h='5242640fu' />"
            + "<gids-designer:empty/>"
            + "</gids-designer:empty-v>"
            + "</gids-designer:empty-v>"
            + "</gids-designer:cons-v>"
            + "</gids-designer:cons-v>"
            + "</gids-designer:cons-v>"
            + "</gids-designer:root>";
    byte[] compressed = new byte[ 2000 ];
    String output = null;
    String encodedString = "";
    Base64 b64 = new Base64();
    byte[] decoded = new byte[ 4096 ];
    String clobStr = null;


    /**
     * xtor
     */
    public SFOUtils()
    {
    }


    /**
     * MAIN is NOT USED
     * @param args the command line arguments
     */
    public static void main( String[] args )
    {
        // TODO code application logic here
        int resLen = 0;
        int compLen = 0;
        String result = "";

        SFOUtils su = new SFOUtils();
//        System.out.println("Original string is " + su.memento.length());

        /* compress */
        compLen = su.deflate( su.memento , su.compressed );
        System.out.println( "Compressed len is " + compLen );
//        System.out.println("/" + su.compressed.toString() + "/");

        /* encode */
        su.encodedString = Base64.encodeBase64String( su.compressed );
        System.out.println( "Compressed and Encoded (" + su.encodedString.length() + " bytes):" );
        System.out.println( "STORE in DB: /" + su.encodedString + "/" );

        /* decode */
        su.decoded = su.b64.decode( su.encodedString );
        System.out.println( "Decoded compressed string:" );
        System.out.println( "/" + su.decoded.toString() + "/" );
//        
        /* uncompress */
        result = "";
        resLen = su.inflate( su.compressed , compLen );
        System.out.println( "Decompressed len is " + resLen );
        System.out.println( "/" + su.homelyPrint( su.output ) + "/" );

        System.out.println( "------------------------------------------" );

        /* get clob */
        //DBConnector dbc = new DBConnector("QC_OWNER", "Qc_owner1234", "DEV");
        //DBConnector dbc = new DBConnector("QC_OWNER", "Qc_owner1234", "TEST");
        DBConnector dbc = new DBConnector( "QC_OWNER" , "april$2008" , "PROD" );

        long clen = dbc.getClobFromDB();
        Clob clob = dbc.getClob();
        System.out.println( "clob is " + clob );
        su.clobStr = dbc.getSfoClobString( clob , clen );
        System.out.println( "Clob string is /" + su.clobStr + "/" );

        //decode 
        su.decoded = su.b64.decode( su.clobStr );
//        System.out.println("Decoded compressed string:");
//        System.out.println("/" + su.decoded.toString() + "/");

        //uncompress 
        result = "";
        resLen = su.inflate( su.compressed , compLen );
        //resLen = su.inflate(su.compressed, su.decoded.length + 2000);
        System.out.println( "su.compressed len is " + su.compressed.length );
        System.out.println( "Compressed len is  " + compLen + ", Decompressed len is " + resLen );

        System.out.println( "/" + su.homelyPrint( su.output ) + "/" );
        System.out.println( "-------------------------------------------" );

        String sfo = su.getSfoFromDB( SfoType.DESIGNER_SFO , dbc );
        System.out.println( SfoType.DESIGNER_SFO.toString() + "\n/" + su.homelyPrint( sfo ) + "/" );
        System.out.println( "......................................" );
        su.writeSfoToFile( SfoType.DESIGNER_SFO , sfo );
//             
        String sfo2 = su.getSfoFromDB( SfoType.ENCAPSULATED_SFO , dbc );
        System.out.println( SfoType.ENCAPSULATED_SFO.toString() + "\n/" + su.homelyPrint( sfo2 ) + "/" );
        su.writeSfoToFile( SfoType.ENCAPSULATED_SFO , sfo2 );
        System.out.println( "......................................" );

        String sfo1 = su.getSfoFromDB( SfoType.ITEM_LAYOUT , dbc );
        System.out.println( SfoType.ITEM_LAYOUT.toString() + "\n/" + su.homelyPrint( sfo1 ) + "/" );
        su.writeSfoToFile( SfoType.ITEM_LAYOUT , sfo1 );

        // Go get the blob
        try
        {
            Blob jpeg = dbc.getJpegFromDB();
            if ( jpeg != null )
            {
                long len = jpeg.length();
                File outfile = new File( "out.jpg" );

                InputStream is = jpeg.getBinaryStream();
                OutputStream os = new FileOutputStream( outfile );
                byte[] buf = new byte[ (int) len ];
                int n = 0;

                while ( ( n = is.read( buf ) ) != -1 )
                {
                    os.write( buf , 0 , n );
                }
                os.flush();
                os.close();
                is.close();
                System.out.println( "Trying to print blob" );

            }

        }
        catch ( Exception e )
        {
            System.err.println( e );
        }

        dbc.closeGidsConnection();
    }


    /**
     * 
     * @param inputString
     * @param output
     * @return 
     */
    public int deflate( String inputString , byte[] output )
    {
        try
        {
            byte[] input = inputString.getBytes( "UTF-16LE" );
            Deflater compressor = new Deflater();
            compressor.setInput( input );
            compressor.finish();
            int compressedDataLength = compressor.deflate( output );
            return compressedDataLength;
        }
        catch ( Exception e )
        {
            System.err.println( e );
            return -1;
        }
    }


    /**
     * 
     * @param input
     * @param len
     * @return 
     */
    public int inflate( byte[] input , int len )
    {
        try
        {
            System.out.println( "in inflate(): len is " + len );
            Inflater decompressor = new Inflater();
            decompressor.setInput( input );
            byte[] result = new byte[ input.length * 1024 ];
            int resultLength = decompressor.inflate( result );
            decompressor.end();
            output = new String( result , 0 , resultLength , "UTF-16LE" );
            return resultLength;
        }
        catch ( Exception e )
        {
            System.err.println( e );
            return -1;
        }
    }


    /**
     * 
     * @param in
     * @return 
     */
    public String homelyPrint( String in )
    {
        String out = in.replaceAll( "><" , ">\n<" );
        return out;
    }



    /**
     * THIS is old and not used
     * @param type
     * @param dbc
     * @return 
     */
    public String getSfoFromDB( SfoType type , DBConnector dbc )
    {
        final int ARRAY_SIZE = 30000;
        String sfo = "";
        decoded = new byte[ ARRAY_SIZE ];
        long clen = dbc.getClobFromDB( type );
        Clob clob = dbc.getClob();
        clobStr = dbc.getSfoClobString( clob , clen );
        System.out.println( type.toString() + ":\n///" + clobStr + "///" );
        decoded = b64.decode( clobStr );
        System.out.println( type.toString() + " decoded compressed:\n//" + decoded.toString() + "//" );
        clobStr = null;

        int resLen = inflate( decoded /*compressed*/ , ARRAY_SIZE/*decoded.length*/ );
        sfo = output;
        //decoded = new byte[2000];
        return sfo;
    }


    /**
     * not used
     * @param type
     * @param sfo 
     */
    public void writeSfoToFile( SfoType type , String sfo )
    {
        try
        {
            //FileWriter fwriter = new FileWriter( "C:\\\\temp\\\\" + type.toString() + ".out" );
            FileWriter fwriter = new FileWriter( type.toString() + ".out" );
            BufferedWriter out = new BufferedWriter( fwriter );
            out.write( sfo );
            out.close();
        }
        catch ( IOException e )
        {
            System.err.println( e );
            e.getMessage();
        }
    }


    /**
     * 
     * @return 
     */
    public String getMemento()
    {
        return memento;
    }


    /**
     * 
     * @param memento 
     */
    public void setMemento( String memento )
    {
        this.memento = memento;
    }


    /**
     * 
     * @return 
     */
    public byte[] getCompressed()
    {
        return compressed;
    }


    /**
     * 
     * @param compressed 
     */
    public void setCompressed( byte[] compressed )
    {
        this.compressed = compressed;
    }


    /**
     * 
     * @return 
     */
    public String getOutput()
    {
        return output;
    }


    /**
     * 
     * @param output 
     */
    public void setOutput( String output )
    {
        this.output = output;
    }


    /**
     * 
     * @return 
     */
    public String getEncodedString()
    {
        return encodedString;
    }

    /**
     * 
     * @param encodedString 
     */
    public void setEncodedString( String encodedString )
    {
        this.encodedString = encodedString;
    }


    /**
     * 
     * @return 
     */
    public Base64 getB64()
    {
        return b64;
    }


    /**
     * 
     * @param b64 
     */
    public void setB64( Base64 b64 )
    {
        this.b64 = b64;
    }


    /**
     * 
     * @return 
     */
    public byte[] getDecoded()
    {
        return decoded;
    }


    /**
     * 
     * @param decoded 
     */
    public void setDecoded( byte[] decoded )
    {
        this.decoded = decoded;
    }


    /**
     * 
     * @return 
     */
    public String getClobStr()
    {
        return clobStr;
    }


    /**
     * 
     * @param clobStr 
     */
    public void setClobStr( String clobStr )
    {
        this.clobStr = clobStr;
    }

}
